package threadcommunication;

import java.util.ArrayList;
import java.util.List;

/**
 * 使用sleep、while死循环实现多个线程间的通讯
 */
public class Demo_01 {
    public static void main(String[] args) {
        MyList list = new MyList();
        ThreadB threadB = new ThreadB(list);
        threadB.setName("B");
        threadB.start();
        ThreadA threadA = new ThreadA(list);
        threadA.setName("A");
        threadA.start();

    }
}

class ThreadA extends Thread {
    private MyList list;

    public ThreadA(MyList list) {
        this.list = list;
    }

    @Override
    public void run() {
        try {
            for(int i = 0; i < 10; i++) {
                list.add();
                System.out.println("添加了" + (i + 1) + "个元素");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ThreadB extends Thread {
    private MyList list;

    public ThreadB(MyList list) {
        this.list = list;
    }

    @Override
    public void run() {
        try {
            while (true) {
                if(list.size() == 5) {
                    System.out.println("==5 ,线程B要退出了");
                    throw new InterruptedException();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
